<template>
  <div ref="mapRef" class="tech-map-container"></div>
</template>

<script setup>
import { ref, onMounted, watchEffect, watch } from 'vue';
import * as echarts from 'echarts';

// Props定义
const props = defineProps({
  data: {
    type: Array,
    default: () => []
  }
});

// 事件定义
const emit = defineEmits([
  'province-click',
  'province-hover', 
  'province-leave',
  'map-blank-click'
]);

onMounted(async () => {
  // 延迟初始化，确保props.data已经传递
  setTimeout(async () => {
    await initMap();
  }, 200);
});

const mapRef = ref(null);
let chart = null;

const initMap = async () => {
  // 销毁旧实例
  if (chart) chart.dispose();
  chart = echarts.init(mapRef.value);

  // 动态加载中国地图数据
  try {
    const response = await fetch('https://geo.datav.aliyun.com/areas_v3/bound/100000_full.json');
    const chinaMapData = await response.json();
    echarts.registerMap('china', chinaMapData);
    console.log('✅ 中国地图数据加载成功');
  } catch (error) {
    console.error('❌ 地图数据加载失败，使用备用方案:', error);
    // 如果加载失败，尝试使用ECharts内置地图
    // 或者显示一个简单的矩形作为占位符
  }

  // 使用props数据或默认数据
  console.log('🗺️ 地图接收到的数据:', props.data)
  console.log('🗺️ 数据长度:', props.data ? props.data.length : 0)
  console.log('🗺️ 数据类型:', typeof props.data, Array.isArray(props.data))
  
  // 强制使用props数据，即使为空也要使用
  const provinceData = props.data || [
    { name: '北京', value: 850, hospitals: [], avgRating: 4.5 },
    { name: '上海', value: 920, hospitals: [], avgRating: 4.6 },
    { name: '广东', value: 980, hospitals: [], avgRating: 4.4 },
    { name: '浙江', value: 880, hospitals: [], avgRating: 4.3 },
    { name: '江苏', value: 900, hospitals: [], avgRating: 4.2 },
    { name: '青海', value: 600, hospitals: [], avgRating: 4.1 },
    { name: '四川', value: 750, hospitals: [], avgRating: 4.0 },
    { name: '湖北', value: 680, hospitals: [], avgRating: 3.9 },
    { name: '山东', value: 720, hospitals: [], avgRating: 3.8 },
    { name: '河南', value: 650, hospitals: [], avgRating: 3.7 },
    { name: '湖南', value: 580, hospitals: [], avgRating: 3.6 },
    { name: '安徽', value: 520, hospitals: [], avgRating: 3.5 },
    { name: '福建', value: 480, hospitals: [], avgRating: 3.4 },
    { name: '江西', value: 450, hospitals: [], avgRating: 3.3 },
    { name: '河北', value: 420, hospitals: [], avgRating: 3.2 },
    { name: '山西', value: 380, hospitals: [], avgRating: 3.1 },
    { name: '辽宁', value: 350, hospitals: [], avgRating: 3.0 },
    { name: '吉林', value: 320, hospitals: [], avgRating: 2.9 },
    { name: '黑龙江', value: 300, hospitals: [], avgRating: 2.8 },
    { name: '陕西', value: 280, hospitals: [], avgRating: 2.7 },
    { name: '甘肃', value: 250, hospitals: [], avgRating: 2.6 },
    { name: '宁夏', value: 200, hospitals: [], avgRating: 2.5 },
    { name: '新疆', value: 180, hospitals: [], avgRating: 2.4 },
    { name: '西藏', value: 150, hospitals: [], avgRating: 2.3 },
    { name: '云南', value: 400, hospitals: [], avgRating: 2.2 },
    { name: '贵州', value: 350, hospitals: [], avgRating: 2.1 },
    { name: '广西', value: 300, hospitals: [], avgRating: 2.0 },
    { name: '海南', value: 200, hospitals: [], avgRating: 1.9 },
    { name: '内蒙古', value: 250, hospitals: [], avgRating: 1.8 },
    { name: '天津', value: 500, hospitals: [], avgRating: 1.7 },
    { name: '重庆', value: 600, hospitals: [], avgRating: 1.6 },
    { name: '台湾', value: 100, hospitals: [], avgRating: 1.5 },
    { name: '香港', value: 80, hospitals: [], avgRating: 1.4 },
    { name: '澳门', value: 30, hospitals: [], avgRating: 1.3 }
  ];

  const option = {
    // 1. 背景与网格（科技感基础）
    backgroundColor: '#050d29',
    graphic: [
      {
        type: 'group',
        children: new Array(40).fill(0).map((_, i) => ({
          type: 'line',
          shape: { x1: i * 30, y1: 0, x2: i * 30, y2: 800 },
          style: { stroke: 'rgba(0, 242, 254, 0.05)' },
        })),
      },
      {
        type: 'group',
        children: new Array(30).fill(0).map((_, i) => ({
          type: 'line',
          shape: { x1: 0, y1: i * 30, x2: 1200, y2: i * 30 },
          style: { stroke: 'rgba(0, 242, 254, 0.05)' },
        })),
      },
    ],

    // 2. 标题与科技感样式
    title: {
      text: '全国医美分布',
      left: 'center',
      top: '20px',
      textStyle: {
        color: '#00f2fe',
        fontSize: 24,
        fontWeight: 'bold',
        textShadow: '0 0 10px rgba(0, 242, 254, 0.5)', // 文字发光
      },
    },

    // 3. 提示框（悬浮交互）
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(10, 20, 40, 0.85)',
      borderColor: '#00f2fe',
      borderWidth: 1,
      textStyle: { color: '#fff' },
      formatter: (params) => {
        console.log('🗺️ Tooltip 参数:', params)
        if (params.componentType === 'series' && params.seriesType === 'map') {
          // 从provinceData中查找完整数据
          const fullData = provinceData.find(p => p.name === params.name || p.name.includes(params.name) || params.name.includes(p.name));
          console.log('🗺️ 完整省份数据:', fullData)
          console.log('🗺️ 查找参数:', { paramsName: params.name, provinceDataNames: provinceData.map(p => p.name) })
          
          if (fullData) {
            const hospitalCount = fullData.value || 0;
            const avgRating = fullData.avgRating || 0;
            console.log(`🗺️ ${fullData.name}: ${hospitalCount} 家医美机构, 平均评分: ${avgRating}`)
            if (fullData.hospitals && fullData.hospitals.length > 0) {
              return `${fullData.name}: ${hospitalCount} 家医美机构<br/>平均评分: ${avgRating.toFixed(1)}`;
            }
            return `${fullData.name}: ${hospitalCount} 家医美机构`;
          }
          return `${params.name}: 0 家医美机构`;
        }
        return `${params.name}: 0 家医美机构`;
      },
    },


    // 5. 地图系列（核心）
    series: [
      {
        name: '医美机构分布',
        type: 'map',
        map: 'china',
        roam: true, // 允许缩放、平移
        label: {
          show: true,
          color: '#89bff8',
          fontSize: 12,
          fontFamily: 'Consolas, monospace', // 科技感字体
        },
        itemStyle: {
          areaColor: 'rgba(10, 20, 40, 0.6)', // 省份默认底色
          borderColor: 'rgba(0, 242, 254, 0.3)', // 省份边框
          borderWidth: 1,
          shadowColor: 'rgba(0, 242, 254, 0.5)', // 发光阴影
          shadowBlur: 10,
        },
        emphasis: {
          itemStyle: {
             areaColor: 'rgba(0, 98, 255, 0.6)', // hover 时高亮色
             borderColor: '#00f2fe',
             borderWidth: 1.5,
             shadowBlur: 10, // 减少阴影模糊，避免闪烁
           },
           label: {
             color: '#00f2fe',
             fontSize: 14,
           },
         },
        data: provinceData,
      },
      // 散点层：增强科技感
      {
        type: 'scatter',
        coordinateSystem: 'geo',
        symbolSize: (val) => val[2] / 10,
        data: provinceData.map((item) => [
          item.name,
          null, // 经纬度可留空，ECharts 自动匹配
          item.value,
        ]),
        itemStyle: {
          color: '#00f2fe',
          shadowColor: '#00f2fe',
          shadowBlur: 10,
        },
        zlevel: 2, // 层级高于地图
      },
    ],
  };

  chart.setOption(option);

  // 添加事件监听器
  chart.on('click', (params) => {
    if (params.componentType === 'series' && params.seriesType === 'map') {
      // 省份点击事件
      const provinceInfo = provinceData.find(p => p.name === params.name || p.name.includes(params.name) || params.name.includes(p.name));
      console.log('🗺️ 点击查找:', { paramsName: params.name, found: !!provinceInfo, provinceDataNames: provinceData.map(p => p.name) });
      emit('province-click', {
        province: params.name,
        provinceData: provinceInfo || { name: params.name, value: 0, hospitals: [], avgRating: 0 }
      });
    } else {
      // 地图空白区域点击事件
      emit('map-blank-click');
    }
  });

  chart.on('mouseover', (params) => {
    if (params.componentType === 'series' && params.seriesType === 'map') {
      // 省份悬停事件
      const provinceInfo = provinceData.find(p => p.name === params.name || p.name.includes(params.name) || params.name.includes(p.name));
      console.log('🗺️ 悬停查找:', { paramsName: params.name, found: !!provinceInfo, provinceDataNames: provinceData.map(p => p.name) });
      emit('province-hover', {
        province: params.name,
        provinceData: provinceInfo || { name: params.name, value: 0, hospitals: [], avgRating: 0 }
      });
    }
  });

  chart.on('mouseout', (params) => {
    if (params.componentType === 'series' && params.seriesType === 'map') {
      // 省份离开事件
      emit('province-leave');
    }
  });
};

// 监听props数据变化，重新渲染地图
watch(() => props.data, (newData, oldData) => {
  console.log('🗺️ 地图数据变化:', {
    newData: newData ? newData.length : 0,
    oldData: oldData ? oldData.length : 0,
    hasChart: !!chart,
    newDataSample: newData && newData.length > 0 ? newData[0] : null
  });
  
  // 强制重新渲染地图，无论数据是否为空
  console.log('🗺️ 强制重新渲染地图');
  setTimeout(() => {
    initMap();
  }, 100);
}, { deep: true, immediate: true });

// 窗口resize时自适应
watchEffect((onInvalidate) => {
  onInvalidate(() => {
    if (chart) chart.resize();
  });
  window.addEventListener('resize', () => chart && chart.resize());
});
</script>

<style scoped>
.tech-map-container {
  width: 100%;
  height: 100%;
}
</style>
